package top.waikin.mooc.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.waikin.mooc.admin.domain.AdminEditDto;
import top.waikin.mooc.admin.service.AdminService;
import top.waikin.mooc.common.api.CommonPage;
import top.waikin.mooc.common.api.CommonResult;
import top.waikin.mooc.entity.Admin;
import top.waikin.mooc.entity.Role;

import java.util.List;

/**
 * 管理员 前端控制器
 */
@RestController
@Api(tags = "AdminController", description = "管理员管理")
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminService adminService;

    // 管理员管理
    @ApiOperation("修改指定管理员")
    @PutMapping("/{id}")
    public CommonResult update(@PathVariable Integer id,
                               @RequestBody @Validated AdminEditDto adminEditDto) {
        boolean b = adminService.update(id, adminEditDto);
        return CommonResult.decide(b);
    }

    @ApiOperation("获取指定管理员")
    @GetMapping("/{id}")
    public CommonResult<Admin> getById(@PathVariable Integer id) {
        Admin admin = adminService.getById(id);
        admin.setPassword(null);
        return CommonResult.success(admin);
    }

    @ApiOperation("根据管理员手机或昵称分页获取管理员列表")
    @GetMapping
    public CommonResult<CommonPage<Admin>> page(@RequestParam(defaultValue = "1") Integer current,
                                                @RequestParam(defaultValue = "10") Integer size,
                                                @RequestParam(required = false) String keyWord) {
        IPage<Admin> page = adminService.page(current, size, keyWord);
        return CommonResult.success(CommonPage.restPage(page));
    }

    // 角色相关
    @ApiOperation("给管理员分配角色")
    @PostMapping("/{id}/role")
    public CommonResult updateRole(@PathVariable Integer id, @RequestParam List<Integer> roleIds) {
        boolean b = adminService.updateRole(id, roleIds);
        return CommonResult.decide(b);
    }

    @ApiOperation("获取管理员角色列表")
    @GetMapping("/{id}/role")
    public CommonResult<List<Role>> getRoleList(@PathVariable Integer id) {
        List<Role> roleList = adminService.getRoleList(id);
        return CommonResult.success(roleList);
    }
}
